package com.blrs.service.poliy.impl;

import java.util.ArrayList;
import java.util.List;

import com.blrs.common.constant.RouteIndex;
import com.blrs.common.core.domain.entity.SysDept;
import com.blrs.common.utils.ReflectionUtils;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.common.utils.uuid.UUID;
import com.blrs.domain.PolicyReception;
import com.blrs.domain.vo.EnterpriseVO;
import com.blrs.domain.vo.FeedBackVo;
import com.blrs.mapper.EnterpriseInfoMapper;
import com.blrs.mapper.PolicyReceptionMapper;
import com.blrs.service.indexInfo.IInfoIndexService;
import com.blrs.service.poliy.IPolicyReleaseService;
import com.blrs.system.mapper.SysDeptMapper;
import com.blrs.system.mapper.SysUploadFileMapper;
import com.blrs.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.blrs.mapper.PolicyReleaseMapper;
import com.blrs.domain.PolicyRelease;
import org.springframework.transaction.annotation.Transactional;

/**
 * 政策发布Service业务层处理
 * @author ruoyi
 * @date 2024-01-09
 */
@Service
public class PolicyReleaseServiceImpl implements IPolicyReleaseService
{
    @Autowired
    private PolicyReleaseMapper policyReleaseMapper;
    @Autowired
    private PolicyReceptionMapper policyReceptionMapper;
    @Autowired
    private EnterpriseInfoMapper enterpriseInfoMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysUploadFileMapper sysUploadFileMapper;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IInfoIndexService infoIndexService;
    /**
     * 查询政策发布
     * 
     * @param permissionId 政策发布主键
     * @return 政策发布
     */
    @Override
    public PolicyRelease selectPolicyReleaseByPermissionId(String id)
    {
        return policyReleaseMapper.selectPolicyReleaseByPermissionId(id);
    }

    /**
     * 查询政策发布列表
     * 
     * @param policyRelease 政策发布
     * @return 政策发布
     */
    @Override
    public List<PolicyRelease> selectPolicyReleaseList(PolicyRelease policyRelease)
    {
        if (SecurityUtils.getUserId()!=1 && SecurityUtils.getUserId()!=2){
            policyRelease.setBelongTo(SecurityUtils.getOrgId());
        }
        List<PolicyRelease> policyReleases = policyReleaseMapper.selectPolicyReleaseList(policyRelease);
        for (PolicyRelease release : policyReleases) {
            release.setUrl(sysUploadFileMapper.selectUrlByCode("policy",release.getUploadFile()));
            release.setReadCount(policyReceptionMapper.selectReadCountByPolicyId(release.getId()));
            if (release.getStatus().equals("已发布")){
               release.setInterestedEnterprise(policyReceptionMapper.selectInterestedEnterprise(release.getId()));
            }
        }
        return policyReleases;
    }

    /**
     * 新增政策发布
     * 
     * @param policyRelease 政策发布
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertPolicyRelease(PolicyRelease policyRelease) throws NoSuchFieldException, IllegalAccessException {
       policyRelease.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        if (policyRelease.getSendType().equals("groupSend")){
            for (String s : policyRelease.getEnterpriseId()) {
                if (StringUtils.isNotEmpty(s)){
                    //先查询对应组织机构id
                    PolicyReception policyReception = new PolicyReception();
                    //根据企业id查询企业名称
                    String enterpriseName = enterpriseInfoMapper.selectEnterpriseInfoByEnterpriseId(s).getEnterpriseName();
                    //根据企业名称查询组织机构id
                    policyReception.setReceiverId(sysDeptMapper.selectByDeptName(enterpriseName).getDeptId());
                    policyReception.setEnterpriseId(s);
                    policyReception.setPolicyId(policyRelease.getId());
                    policyReceptionMapper.insertPolicyReception(policyReception);
                }
            }

        }else {
            //说明是一键发送
            // 获取所有的入驻企业id
            List<SysDept> deptList = sysDeptMapper.selectOrgList(null);
            if (deptList != null && !deptList.isEmpty()) {
                List<PolicyReception> policyReceptions = new ArrayList<>();
                for (SysDept sysDept : deptList) {
                    PolicyReception policyReception = new PolicyReception();
                    policyReception.setPolicyId(policyRelease.getId());
                    policyReception.setReceiverId(sysDept.getDeptId());
                    policyReceptions.add(policyReception);
                }
                // 批量插入
                policyReceptionMapper.batchInsertPolicyReception(policyReceptions);
            }

        }
        //状态
        policyRelease.setStatus("审核");
        policyRelease.setReceiverId(String.join(",",policyRelease.getEnterpriseId()));
        policyRelease.setSendUnit(SecurityUtils.getOrgName());
        ReflectionUtils.setCommonPrivateProperty(policyRelease);
        policyRelease.setBelongTo(SecurityUtils.getOrgId());
        policyRelease.setOrganizationName(SecurityUtils.getOrgName());
        return policyReleaseMapper.insertPolicyRelease(policyRelease);
    }

    /**
     * 修改政策发布
     * 
     * @param policyRelease 政策发布
     * @return 结果
     */
    @Override
    public int updatePolicyRelease(PolicyRelease policyRelease)
    {
        //判断传入的是一键发送还是分类群发
        if (policyRelease.getSendType().equals("groupSend")){
            //说明是分类群发,删除旧的接收表数据，添加新的
            policyReceptionMapper.deletePolicyReceptionByPolicyId(policyRelease.getId());
            for (String s : policyRelease.getEnterpriseId()) {
                if (StringUtils.isNotEmpty(s)) {
                    //先查询对应组织机构id
                    PolicyReception policyReception = new PolicyReception();
                    //根据企业id查询企业名称
                    String enterpriseName = enterpriseInfoMapper.selectEnterpriseInfoByEnterpriseId(s).getEnterpriseName();
                    //根据企业名称查询组织机构id
                    policyReception.setReceiverId(sysDeptMapper.selectByDeptName(enterpriseName).getDeptId());
                    policyReception.setEnterpriseId(s);
                    policyReception.setPolicyId(policyRelease.getId());
                    policyReceptionMapper.insertPolicyReception(policyReception);
                }
            }
        }else {
            //说明是一键发送
            if (policyReleaseMapper.selectIsSend(policyRelease.getId()).equals("groupSend")){
                //说明修改之前为分类群发
                policyReceptionMapper.deletePolicyReceptionByPolicyId(policyRelease.getId());
                //获取所有的入驻企业id
                List<SysDept> deptList = sysDeptMapper.selectOrgList(null);
                if (deptList != null && !deptList.isEmpty()) {
                    List<PolicyReception> policyReceptions = new ArrayList<>();
                    for (SysDept sysDept : deptList) {
                        PolicyReception policyReception = new PolicyReception();
                        policyReception.setPolicyId(policyRelease.getId());
                        policyReception.setReceiverId(sysDept.getDeptId());
                        policyReceptions.add(policyReception);
                    }
                    // 批量插入
                    policyReceptionMapper.batchInsertPolicyReception(policyReceptions);
                }
            }
        }
        return policyReleaseMapper.updatePolicyRelease(policyRelease);
    }

    /**
     * 批量删除政策发布
     * 
     * @param permissionIds 需要删除的政策发布主键
     * @return 结果
     */
    @Override
    public int deletePolicyReleaseByPermissionIds(String[] permissionIds)
    {
        return policyReleaseMapper.deletePolicyReleaseByPermissionIds(permissionIds);
    }

    /**
     * 删除政策发布信息
     * 
     * @param permissionId 政策发布主键
     * @return 结果
     */
    @Override
    public int deletePolicyReleaseByPermissionId(String permissionId)
    {
        return policyReleaseMapper.deletePolicyReleaseByPermissionId(permissionId);
    }

    @Override
    public List<PolicyRelease> selectPolicyReleaseListByExamine(PolicyRelease policyRelease) {
        List<PolicyRelease> policyReleases = policyReleaseMapper.selectPolicyReleaseList(policyRelease);
        for (PolicyRelease release : policyReleases) {
            release.setUrl(sysUploadFileMapper.selectUrlByCode("policy",release.getUploadFile()));
        }
        return policyReleases;
//       if (SecurityUtils.getOrgId().equals(100L)){
//           policyRelease.setSendType("oneClick");
//
//           return policyReleases;
//       }else {
//         policyRelease.setSendType("groupSend");
//         policyRelease.setBelongTo(SecurityUtils.getOrgId());
//         policyRelease.setExamineId(SecurityUtils.getUserId());
//           List<PolicyRelease> policyReleases = policyReleaseMapper.selectPolicyReleaseList(policyRelease);
//           for (PolicyRelease release : policyReleases) {
//               release.setUrl(sysUploadFileMapper.selectUrlByCode("policy",release.getUploadFile()));
//           }
//           return policyReleases;
//       }
    }

    @Override
    public int examinePolicy(PolicyRelease policyRelease) {
        infoIndexService.createAndInsertInfoIndex(
                policyRelease.getId(),
                policyRelease.getPolicyThemes(),
                policyRelease.getOrganizationName(),
                policyRelease.getBelongTo(),
                "政策信息",
                RouteIndex.POLICY_RELEASE,
                2116L,
                policyRelease.getSendType()
        );
       return policyReleaseMapper.updatePolicyStatus(policyRelease.getId());
    }

    @Override
    public List<PolicyRelease> selectPolicyReleaseListByReceive(PolicyRelease policyRelease) {
        policyRelease.setBelongTo(SecurityUtils.getOrgId());
        List<PolicyRelease> policyReleaseList=policyReleaseMapper.selectPolicyReleaseListByReceiveId(policyRelease);
        for (PolicyRelease release : policyReleaseList) {
            release.setUrl(sysUploadFileMapper.selectUrlByCode("policy",release.getUploadFile()));
            release.setFeedback(policyReceptionMapper.selectFeedbackByPolicyId(release.getId(),SecurityUtils.getOrgId()));
        }
        return policyReleaseList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int terminationPolicy(PolicyRelease policyRelease) {
        policyReceptionMapper.deletePolicyReceptionByPolicyId(policyRelease.getId());
        return policyReleaseMapper.updatePolicyReleaseByStatus(policyRelease);
    }

    /**
     * 阅读次数
     *
     * @param id
     * @param receiveId
     * @return
     */
    @Override
    public int read(String id, Long receiveId) {
        return policyReceptionMapper.updateReadCount(id,receiveId);
    }

    @Override
    public int feedback(FeedBackVo feedBackVo) {
        return policyReceptionMapper.updateFeedback(feedBackVo);
    }

    @Override
    public List<EnterpriseVO> selectEnterprise(String id) {
        List<String> list = policyReceptionMapper.selectEnterprise(id);
        ArrayList<EnterpriseVO> enterpriseVOs = new ArrayList<>();
        for (String s : list) {
            EnterpriseVO enterpriseVO = new EnterpriseVO();
            enterpriseVO.setDeptName(s);
            SysDept sysDept = sysDeptMapper.selectByDeptName(s);
            enterpriseVO.setPhone(sysDept.getPhone());
            enterpriseVO.setContacts(sysDept.getContacts());
            enterpriseVOs.add(enterpriseVO);
        }
        return enterpriseVOs;
    }
}
